<template>
  <audio
    ref="audio"
    :src="src"
    :preload="preload"
    @canplay="onCanplay"
    @canplaythrough="onCanplaythrough"
    @play="onPlay"
    @pause="onPause"
    @ended="onEnded"
    @timeupdate="onTimeupdate"
    @volumechange="onVolumechange"></audio>
</template>

<script>
import autoplayHelper from '../../utils/media/helpers/autoplay'

export default {
  name: 'a9-audio',
  props: {
    src: String,
    preload: { // 可选值auto|metadata|none
      type: String,
      default: 'auto'
    },
    muted: {
      type: Boolean,
      default: false
    },
    volume: { // 取值范围为[0, 1]
      type: Number,
      default: 1
    },
    loop: {
      type: Boolean,
      default: true
    },
    autoplay: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      paused: false // 播放状态
    }
  },
  mounted () {
    let audio = this.$refs.audio
    // 设置是否静音
    audio.muted = this.muted
    // 设置是否循环
    audio.loop = this.loop
    // 初始化播放状态
    this.paused = audio.paused

    this.autoplayReady(() => {
      if (this.autoplay) {
        this.play()
      }
    })
  },
  methods: {
    autoplayReady (done) {
      autoplayHelper.autoplayReady([this.$refs.audio], () => {
        done()
      })
    },
    play () {
      return autoplayHelper.play(this.$refs.audio).then(() => {
        this.paused = false
      })
    },
    pause () {
      return autoplayHelper.pause(this.$refs.audio).then(() => {
        this.paused = true
      })
    },

    /**
     * 事件
     */
    onCanplay () {
      this.$emit('canplay')
    },
    onCanplaythrough () {
      this.$emit('canplaythrough')
    },
    onPlay () {
      this.paused = false
      this.$emit('play')
    },
    onPause () {
      this.paused = true
      this.$emit('pause')
    },
    onEnded () {
      this.$emit('ended')
    },
    onTimeupdate () {
      this.$emit('timeupdate')
    },
    onVolumechange () {
      this.$emit('volumechange')
    }
  }
}
</script>
